package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"

	"gopkg.in/gomail.v2"
)

// 发送邮件
/* func sendMail(a []Alert) (err error) {
	smtphost := configMap["email"]["smtp"]
	port := configMap["email"]["port"]
	from := configMap["email"]["from"]
	password := configMap["email"]["password"]
	tomail := processToMail(configMap["email"]["tomail"])

	header := make(map[string]string)
	header["From"] = "监控告警<" + from + ">"
	header["To"] = configMap["email"]["tomail"]
	header["Subject"] = fmt.Sprintf("【Prometheus】%s", a[0].alertname)
	header["Content-Type"] = "text/html;charset=UTF-8"

	message := ""
	for k, v := range header {
		message += fmt.Sprintf("%s:%s\r\n", k, v)
	}
	message += "\r\n" + processAlertToString(a)
	// fmt.Println(message)
	auth := smtp.PlainAuth("", from, password, smtphost)
	err = smtp.SendMail(fmt.Sprintf("%s:%s", smtphost, port), auth, from, tomail, []byte(message))
	if err != nil {
		return fmt.Errorf("smtp.SendMail 处理错误 %v", err)
	}
	return
} */

func sendMail(a []Alert) (err error) {
	smtphost := configMap["email"]["smtp"]
	port, _ := strconv.Atoi(configMap["email"]["port"])
	from := configMap["email"]["from"]
	password := configMap["email"]["password"]
	tomail := processToMail(configMap["email"]["tomail"])

	m := gomail.NewMessage()
	m.SetHeader("From", from)
	m.SetHeader("To", tomail...)
	// m.SetAddressHeader("Cc", "dan@example.com", "Dan")
	m.SetHeader("Subject", fmt.Sprintf("【Prometheus】%s", a[0].alertname))
	m.SetBody("text/html", processAlertToString(a))
	// m.Attach("/home/Alex/lolcat.jpg")

	d := gomail.NewDialer(smtphost, port, from, password)

	if err := d.DialAndSend(m); err != nil {
		panic(err)
	}
	return
}

// 邮件处理handler
func emailHandler(w http.ResponseWriter, r *http.Request) {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Fprintf(w, "请求参数非法")
		return
	}
	alert, err := processRequest(body)
	if err != nil {
		fmt.Fprintf(w, "请求参数处理失败")
		return
	}
	// fmt.Println(alert.startsAt.Format("2006-01-02 15:04:05"))
	// fmt.Println(alert.endsAt.Format("2006-01-02 15:04:05"))
	err = sendMail(alert)
	if err != nil {
		fmt.Println(err)
		fmt.Fprintf(w, "邮件发送失败%v", err)
		return
	}
	if configMap["globals"]["mysql"] == "on" {
		for _, a := range alert {
			err = insertRow(a, "邮件")
			if err != nil {
				fmt.Println(err)
				fmt.Fprintf(w, "邮件发送记录入库失败%v", err)
				return
			}
		}
	}
}
